<template>
  <div>
    <!-- 搜索表单 -->
    <user-search
      v-if="searchData.length > 0"
      :searchData="searchData"
      @search="reload"
    />
    <!-- 表格 -->
    <ele-pro-table
      v-if="cate"
      ref="tableRef"
      height="calc(100vh - 310px)"
      :needPage="false"
      :toolkit="[]"
      :row-key="(record) => record.id"
      :columns="columns"
      :datasource="list"
      v-model:selection="selection"
      @update:selection="onSelectionChange"
      :scroll="{ x: 'max-content' }"
    >
      <template #toolbar>
        <slot name="toolbar"></slot>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.type === 'link'">
          <!-- <router-link :to="'/system/user-info?id=' + record.userId">{{ record.code }}</router-link> -->
          <a @click="toDetail(record, column.extra)">{{ record.code }}</a>
        </template>
        <template v-if="column.type === 'image'">
          <img :src="record.logo_path" class="logo" />
        </template>
        <template v-if="column.name === 'status'">
          <a-switch
            :checked="record.status == 1"
            @change="switchChange($event, column, record)"
          />
        </template>
        <template v-if="column.name === 'exp'">
          <a-input v-model:value="record.exp" placeholder="请输入" />
        </template>
        <template v-if="column.name === 'number'">
          <a-select
            optionFilterProp="label"
            :options="options"
            allow-clear
            v-model:value="record.number"
            placeholder="请选择"
            @change="numChange($event, record)"
            autocomplete="off"
            style="width: 200px"
          />
        </template>
        <template v-if="column.name === 'check_type'">
          <a-radio-group
            v-model:value="record.check_type"
            @change="checkTypeChange($event, record)"
          >
            <a-radio :value="1" class="margin-x-20">人工审核</a-radio>
            <a-radio :value="2" class="margin-x-20">自动审核</a-radio>
          </a-radio-group>
        </template>
        <template v-else-if="column.key === 'action'">
          <slot name="optBtn" :record="record"></slot>
          <a-space>
            <!-- 此处v-permission的值需要做处理，权限接口返回的权限前面没有“/”此处接口返回的权限开头是“/”，所以要接去后传入权限校验方法 -->
            <a
              v-for="item in column.param"
              v-permission="item.url"
              :key="item.url"
              @click="defineFn(item, record)"
              >{{ item.name }}</a
            >
          </a-space>
        </template>
        <template v-else> </template>
      </template>
    </ele-pro-table>

    <div style="margin: 20px 0 0 0">
      <a-space>
        <a-button type="primary" @click="submit()">保存</a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick, defineExpose } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import UserSearch from '@/components/zbTable/components/user-search.vue';
  import formatColumns from '@/utils/tableColumnsFormat';
  import { useRouter } from 'vue-router';
  import { actionFn } from '@/utils/action.js';
  import { edit_rule } from '@/api/setting/receipts_code_rule';
  import { edit_check_rule } from '@/api/setting/receipts_check_rule';
  const router = useRouter();
  const { push } = useRouter();
  const props = defineProps({
    apiFun: Function,
    type: String,
    cate: String,
    data: Object
  });
  const emit = defineEmits(['action']);
  // 表格实例
  const tableRef = ref(null);
  // 表格列配置
  let columns = ref([]);
  // 表格搜索动态表单
  let searchData = ref([]);
  // 表格选中数据
  const selection = ref([]);
  // 触发父级方法数组
  const emitsArr = ref([]);
  const cate = ref(null);
  const options = ref([
    {
      label: '5位',
      value: '5'
    },
    {
      label: '6位',
      value: '6'
    },
    {
      label: '7位',
      value: '7'
    },
    {
      label: '8位',
      value: '8'
    },
    {
      label: '9位',
      value: '9'
    },
    {
      label: '10位',
      value: '10'
    }
  ]);
  const list = ref([]);
  cate.value = props.cate;
  columns.value = [
    { field: 'name', name: '会员等级' },
    { field: 'name', name: '等级名称' },
    { field: 'name', name: '累计积分值自动升级' }
  ];

  onMounted(() => {
    console.log('====', props.data);
  });

  // 表格数据源
  const datasource = ({ page, limit, where }) => {
    return props.apiFun({
      page,
      limit,
      page_size: 9999,
      cate: cate.value,
      filters: {
        ...where
      }
    });
  };
  // 表头/搜索栏，数据
  /* props.apiFun({cate:cate.value}).then(async (res) => {
		columns.value = await formatColumns(res.columns);
		searchData.value = res.searchData;
		list.value = res.list;
		hideSelection();
	}); */
  const numChange = (e, record) => {
    console.log(e, record);
  };
  const checkTypeChange = (e, record) => {
    console.log(e, record);
  };
  const checkCate = (data) => {
    console.log(data);
    cate.value = data;
    props.apiFun({ cate: cate.value }).then(async (res) => {
      columns.value = await formatColumns(res.columns);
      searchData.value = res.searchData;
      list.value = res.list;
      hideSelection();
    });
  };

  const submit = () => {
    console.log('&&&', list.value);
    let arr = [];
    if (props.type == 'code') {
      list.value.forEach((item) => {
        arr.push({
          id: item.id,
          exp: item.exp,
          number: item.number
        });
      });
      edit_rule({
        datas: arr
      })
        .then((res) => {
          message.success(res.msg);
          tableRef?.value?.reload();
        })
        .catch((e) => {
          message.error(e.message || e);
        });
    } else if (props.type == 'check') {
      list.value.forEach((item) => {
        arr.push({
          id: item.id,
          check_type: item.check_type
        });
      });
      edit_check_rule({
        datas: arr
      })
        .then((res) => {
          message.success(res.msg);
          tableRef?.value?.reload();
        })
        .catch((e) => {
          message.error(e.message || e);
        });
    }
  };
  /* 搜索 */
  const reload = (where) => {
    console.log('000000');
    selection.value = undefined;
    tableRef?.value?.reload({
      page: 1,
      where
    });
  };
  // 触发父级方法
  const defineFn = (actionData, rowData) => {
    const data = {
      action_data: actionData,
      row_data: rowData
    };
    console.log(data);
    emit('action', data);
  };

  // 如果要动态控制是否开启多选列可以将 selection 赋值为 undefined
  const hideSelection = () => {
    selection.value = undefined;
  };

  // 如果要动态控制是否开启多选列可以将 selection 赋值为 undefined
  const changeSelection = (val) => {
    console.log('是否显示选择框', val);
    if (val) {
      selection.value = [];
    } else {
      if (
        typeof selection.value == undefined ||
        typeof selection.value == 'object'
      ) {
        selection.value = undefined;
      } else {
        selection.value = [];
      }
    }
  };
  //选中的值发生改变是触发父组件的方法并传值
  const onSelectionChange = (selection) => {
    console.log('选择的是', selection);
    selection.value = selection;
    emit('getselection', selection);
  };
  //触发父级编辑或删除
  const actionOpts = (type, data) => {
    emit('actionOpt', type, data);
  };
  // siwtchchange
  const switchChange = async (e, column, record) => {
    const url = router.currentRoute.value.path.split('/');
    const apiUrl = `/${url[1]}/${url[2]}/quick_edit`;
    await actionFn(
      {
        url: apiUrl
      },
      {
        id: record.id,
        field: column.field,
        value: e ? '1' : '0'
      },
      reload
    );
  };

  const toDetail = (record, url) => {
    console.log('看详情');
    let r = router.currentRoute.value.path.split('/');
    let newUrl = `/${r[1]}/${r[2]}/detail`;
    push({
      path: newUrl,
      query: {
        code: record.code
      }
    });
  };
  // **重点！！这里需要使用defineExpose暴露出去**
  defineExpose({
    reload,
    changeSelection,
    checkCate
  });
</script>

<script>
  export default {
    name: 'SystemUser'
  };
</script>

<style>
  .logo {
    width: 40px;
  }
</style>
